package com.guli.order.listener;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.guli.order.service.OrderService;
import com.guli.order.vo.PayAsyncVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author zzb
 * @Date 2024/4/23 17:12
 * @Version 1.0
 */
@RestController
@Slf4j
public class OrderPayedListener {
    @Autowired
    OrderService orderService;
    @Value("${alipay.alipayPublicKey}")
    String alipayPublicKey;


    /**
     * 异步验签
     * @param request
     * @param payAsyncVo
     * @return
     */
    @PostMapping("/payed/notify")
    public String handleAlipayed(HttpServletRequest request, @ModelAttribute PayAsyncVo payAsyncVo) {
        //输出日志
        log.info("支付宝回调......");
        //获取支付宝POST过来反馈信息
       /* Map<String, String> params = new HashMap<>();*/
        Map requestParams =  request.getParameterMap();
        /*for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }*/
        try {
            boolean flag = AlipaySignature.rsaCheckV1(requestParams, alipayPublicKey, "UTF-8", "RSA2");
            if (flag) {
                return orderService.handlePayResult(payAsyncVo);
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "fail";
    }

}
